﻿using System;
using System.Linq;
using System.Text;
using System.Collections;
using RAP.Framework.Libary.Utils;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using RAP.Framework.Libary.DomTemplateBuilder.Interface;
using RAP.Framework.Libary.DomTemplateBuilder.Element.Parameter;
using RAP.Framework.Libary.DomTemplateBuilder.Element;
using System.Collections.Generic;

namespace RAP.Framework.Libary.DomTemplateBuilder.Handler.Parameter
{
	/// <summary>
	/// 参数节点的Handler
	/// </summary>
	public class ParameterHandler : PropertyElementHandler
	{
		/// <summary>
		/// 参数查询的Key：ParameterContext
		/// </summary>
		public static string PARAMETER_CONEXT_KEY = "ParameterContext";

		/// <summary>
		/// CurrentIndex
		/// </summary>

		public static string PARAMETER_CONEXT_CURRENT_INDEX_KEY = "CurrentIndex";

		/// <summary>
		/// Parameters
		/// </summary>
		public static string PARAMETER_CONEXT_PARAMETERS_KEY = "Parameters";

		/// <summary>
		/// \[[^\[\]]+\]{1}$
		/// </summary>
		public static Regex INDEX_PARAMETER_TAG = new Regex( @"\[[^\[\]]*\]{1}$", RegexOptions.Compiled );

		/// <summary>
		/// 向指定的context对象中的ParameterContext对象的Parameters集合添加一个参数值，并使对应的CurrentIndex加1
		/// </summary>
		public static Func<ITemplateRenderContext, string, object, string> AddContextParameter = ( ITemplateRenderContext context, string paramName, object paramValue ) =>
		{
			var paramContext = context.Parameters;
			if ( INDEX_PARAMETER_TAG.IsMatch( paramName ) )
			{
				var match = INDEX_PARAMETER_TAG.Match( paramName );
				var format = match.Captures.First<Capture>().Value;
				var paramNamePrefix = paramName.Substring( 0, paramName.Length - format.Length );
				format = format.Trim( '[', ']' );
				var paramIndex = paramContext.CurrentIndex;
				paramName = $"{paramNamePrefix}{paramIndex.ToString( format )}";
			}
			paramContext.AddParameter( paramName, paramValue );
			return paramName;
		};

		/// <summary>
		/// 
		/// </summary>
		/// <param name="writer"></param>
		/// <param name="rootParamObject"></param>
		/// <param name="parentParamObject"></param>
		/// <param name="context"></param>
		public override void DoRender( StringBuilder writer, object rootParamObject, object parentParamObject, ITemplateRenderContext context )
		{
			var paramObject = this.GetParamObject( rootParamObject, parentParamObject, context );
			var ele = this.Element as ParameterElement;
			var propertyValue = this.GetPropertyValue( rootParamObject, parentParamObject, context );
			if ( propertyValue != null )
			{
				propertyValue = propertyValue.ConvertValue( ele.Type.Value );
			}
			AddContextParameter( context, ele.Property, propertyValue );
			base.DoRender( writer, rootParamObject, paramObject, context );
		}
	}
}
